<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-14 09:09:09
 * @LastEditors: whereamazinghappen 306702547@qq.com
 * @LastEditTime: 2023-10-19 20:13:46
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\boardVIew\zjContribution\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="dashboard-container">
    <!-- <div class="title">中交考核贡献度看板</div> -->
    <div class="header-qwl">
      <div>
        <el-tabs v-model="state.activeName">
          <el-tab-pane label="总览" name="total">
            <template #label>
              <span class="custom-tabs-label"> 总览 </span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="列表" name="list">
            <template #label>
              <span class="custom-tabs-label"> 列表 </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="actions">
      <el-button type="primary" @click="editOrSaveBtn" plain v-if="state.activeName == 'list'">{{
        state.editType == 'edit' ? '编辑' : '保存'
      }}</el-button>
      <el-button type="primary" @click="updateDataBtn" plain>更新数据</el-button>
      <el-button type="primary" @click="exportExcel" plain v-if="state.activeName == 'list'"
        >导出Excel</el-button
      >
    </div>
    <el-row
      style="height: calc(100% - 55px); padding-top: 20px"
      v-show="state.activeName == 'total'"
    >
      <el-col :span="14" style="padding-right: 10px">
        <div class="chart-container" ref="zjeharts" style="width: 100%; height: 100%"></div>
      </el-col>
      <el-col :span="10">
        <div class="table-box">
          <div class="table-title">
            <span class="title-span"
              >贡献排名
              <div class="title-divide"></div>
            </span>
            <div class="date-picker">
              <el-date-picker
                v-model="searchFrom.age"
                type="year"
                style="width: 100px"
                value-format="YYYY"
                placeholder="选择年份"
                :clearable="false"
                @change="ageChange"
              />
            </div>
          </div>
          <!-- height="calc(100% - 60px)" -->
          <el-table
            :data="state.table_list"
            style="width: 100%; margin-top: 5px"
            :row-style="rowStyle"
            :cell-style="cellStyle"
          >
            <el-table-column prop="rank" align="center" width="100" label="排名" />
            <el-table-column prop="companyName" align="center" label="单位名称" />
            <el-table-column prop="totalScore" align="center" label="贡献度" width="80" />
          </el-table>
        </div>
      </el-col>
    </el-row>
    <div class="table-bg" style="padding-top: 20px" v-show="state.activeName == 'list'">
      <div style="text-align: center; padding: 10px; color: white">
        {{ searchFrom.age }}年中交科技创新考核-各单位科技贡献度
      </div>
      <el-table
        :data="state.complex_table_list"
        :span-method="arraySpanMethod"
        :header-cell-style="headerCellStyle"
        border
        style="width: 100%"
      >
        <el-table-column prop="indexType1" align="center" label="类指标">
          <template #default="scope">
            {{ scope.row.indexType1.name }}
          </template>
        </el-table-column>
        <el-table-column prop="indexType2" width="200px" align="center" label="模块指标">
          <el-table-column align="center" prop="indexType2">
            <template #default="scope">
              {{ scope.row.indexType2 ? scope.row.indexType2.name : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="indexType2_li">
            <template #default="scope">
              {{ scope.row.indexType2_li ? scope.row.indexType2_li.name : '' }}
            </template>
          </el-table-column>
        </el-table-column>
        <!-- <el-table-column prop="indexType2_li" width="200px" align="center" label="模块指标2">
          <template #default="scope">
            {{ scope.row.indexType2_li ? scope.row.indexType2_li.name : '' }}
          </template>
        </el-table-column> -->
        <el-table-column prop="indexType3" align="center" label="子指标">
          <template #default="scope">
            {{ scope.row.indexType3 ? scope.row.indexType3.name : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="annualScore" align="center" label="年度标准分值">
          <el-table-column prop="annualScore" align="center">
            <template #default="scope">
              {{ scope.row.annualScore }}
            </template>
          </el-table-column>
          <el-table-column prop="annualSumScore" align="center">
            <template #default="scope">
              {{ scope.row.annualSumScore }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="finalScore" align="center" width="100px" label="最终得分">
          <template #default="scope">
            {{ scope.row.finalScore || '' }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="finalScore" align="center" width="100px" label="最终得分">
          <template #default="scope">
            <input type="text" style="width: 80px" />
            <el-input v-model="data.value" style="width: 80px"></el-input>
          </template>
        </el-table-column> -->
        <el-table-column
          v-for="c in state.company_list"
          :key="c.id"
          :prop="'cs' + c.id"
          align="center"
          width="120px"
          :label="c.companyName"
        >
          <template #default="scope">
            <div v-if="scope.row['cs' + c.id]">
              <span v-if="scope.row._rowType">{{ scope.row['cs' + c.id].score }}</span>
              <div v-else>
                <span v-if="state.editType == 'edit' && scope.row['cs' + c.id].indexId">{{
                  scope.row['cs' + c.id].score
                }}</span>
                <!-- <el-input
                  v-else-if="state.editType == 'save' && scope.row['cs' + c.id].indexId"
                  v-model="scope.row['cs' + c.id].score"
                  style="width: 80px"
                ></el-input> -->
                <input
                  class="table-input"
                  v-else-if="state.editType == 'save' && scope.row['cs' + c.id].indexId"
                  :maxlength="5"
                  v-model="scope.row['cs' + c.id].score"
                  type="text"
                  style="width: 80px"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="companyScoreSmallSum" align="center" label="各单位成绩小计" />
      </el-table>
    </div>
  </div>
</template>
<script lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as api from '@/views/examineManage/api/boardView'
import { windowResize } from '@/views/common'
import { getCompanyListRequest } from '@/views/examineManage/api/examineManage'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import pubFc from '@/views/examineManage/utils'
import { fontSizeRem, NumberCheck } from '@/utils/utils'
import { ElLoading } from 'element-plus'

export default {
  setup() {
    let data = reactive({
      value: '',
    })
    const zjeharts = ref()
    const searchFrom = reactive({
      //查询
      age: '',
    })

    // const refreshPage:any=inject('refreshPage', Function, true);
    // let annualId=route.query.id;
    const onResizeHandler = () => {
      windowResize(100, () => {
        myEharts.resize()
      })
    }
    function changeHandler(event) {
      console.log(event.target.value)
    }
    let myEharts

    // const changeHandler = (e, scope, c) => {
    //   console.log(e, 'inputValuex')
    //   // scope.row['cs' + c.id].score = NumberCheck(scope.row['cs' + c.id].score)
    // }
    onMounted(() => {
      console.log('onMounted');
      myEharts = echarts.init(zjeharts.value)
      doHandleYear()
      refreshPage()
      window.addEventListener('resize', onResizeHandler, false)
    })

    onUnmounted(() => {
      window.removeEventListener('resize', onResizeHandler, false)
    })

    const refreshPage = () => {
      state.complex_table_list = []
      state.company_list = []
      state.complex_list = []
      gettargetlist()
      getComxlist()
    }
    // const changeActive=()=>{
    //   if(state.activeName=='total'){

    //   }else{

    //   }
    // }
    let state = reactive<any>({
      table_list: [],
      complex_list: [],
      complex_table_list: [],
      activeName: 'total',
      company_list: [],
      rowSpan1: {},
      editType: 'edit',
    })
    const updateDataBtn = () => {
      api.updateConDataRequest(searchFrom).then((res) => {
        refreshPage()
      })
    }
    const editOrSaveBtn = () => {
      if (state.editType == 'edit') {
        state.editType = 'save'
      } else {
        console.log(state.complex_table_list)
        let params: any = []
        state.complex_table_list.map((item: any) => {
          state.company_list.map((cl) => {
            if (item[`cs${cl.id}`] && item[`cs${cl.id}`].indexId) {
              params.push(item[`cs${cl.id}`])
            }
          })
        })
        console.log('params', params)
        const loading = ElLoading.service({
          lock: true,
        })
        api.saveConDataRequest(params).then((res) => {
          ElMessage.success('成功保存')
          state.editType = 'edit'
          loading.close()
          refreshPage()
        })
      }
    }
    const exportExcel = () => {
      api
        .exportConDataRequest({
          ...searchFrom,
        })
        .then((res) => {
          console.log(res, 'exportExcel')

          const { data, headers } = res
          pubFc.downloadFunc(data, headers)
        })
    }
    let colorList = [
      '#C1232B',
      '#B5C334',
      '#FCCE10',
      '#E87C25',
      '#27727B',
      '#FE8463',
      '#9BCA63',
      '#FAD860',
      '#F3A43B',
      '#60C0DD',
      '#D7504B',
      '#C6E579',
      '#F4E001',
      '#F0805A',
      '#26C0C0',
    ]
    const initEcharts = () => {
      let xdata: Array<string> = []
      let ydata: Array<string> = []
      for (let i = 0; i < state.table_list.length; i++) {
        xdata.push(state.table_list[i].companyName + '\n\n' + state.table_list[i].rank)
        ydata.push(state.table_list[i].totalScore)
      }
      myEharts.setOption({
        title: {
          text: '贡献度排行',
          left: 'center',
          padding: 20,
          textStyle: {
            fontSize: 20,
            color: '#FFF',
          },
        },
        grid: {
          left: '6%',
          right: '6%',
          bottom: '30',
          top: '15%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: xdata,
          name: '排名',
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              color: 'rgba(131,101,101,0.2)',
              type: 'dashed',
            },
          },
          axisLine: {
            show: true,
          },
          name: '得分',
        },
        series: [
          {
            data: ydata,
            type: 'bar',
            barMaxWidth: 50,
            label: {
              show: true,
            },
            barWidth: fontSizeRem(0.3),
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr =
                  params.value > 0
                    ? [colorList[Math.floor(Math.random() * 15)], '#08103B']
                    : ['#08103B', colorList[Math.floor(Math.random() * 15)]]
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
          },
        ],
      })
    }

    const getComxlist = () => {
      //获取复杂的列表数据
      getCompanylist().then((res) => {
        zjconBoardlist()
      })
    }
    const getCompanylist = () => {
      return new Promise((resolve) => {
        getCompanyListRequest({}).then((res) => {
          state.company_list = res.data.data
          resolve(true)
        })
      })
    }
    const ageChange = () => {
      refreshPage()
    }
    const doHandleYear = () => {
      var myDate = new Date()
      searchFrom.age = myDate.getFullYear() + ''
    }

    const gettargetlist = () => {
      //获取table列表
      api
        .zjconBoardRequest({
          ...searchFrom,
        })
        .then((res) => {
          state.table_list = res.data.data
          initEcharts()
        })
    }

    const zjconBoardlist = () => {
      api.zjconBoardlistRequest(searchFrom).then((res) => {
        // state.complex_list=res.data.data;
        let lastArr = res.data.data.splice(res.data.data.length - 1, 1)
        let obj = {
          indexType1: {
            name: lastArr[0]?.name,
          },
          annualScore: lastArr[0].sumScore,
          companyScoreSmallSum: lastArr[0].sumCompanyScoreSmallSum,
          finalScore: lastArr[0].sumFinalScore,
          _rowType: 'sumRow',
        }
        lastArr[0].sumCompanyScoreList.map((cs) => {
          obj[`cs${cs.companyId}`] = {
            score: cs.score,
          }
        })
        dealDataBefore(res.data.data)
        dealDataRowCol()
        state.complex_list.push(obj)
        state.complex_table_list = state.complex_list
        console.log(state.complex_table_list,'state.complex_table_list');
      })
    }
    const dealDataRowCol = () => {
      //处理合并行或合并列
      let rowSpan1: any = {},
        rowSpan2: any = {},
        rowSpan2_li: any = {}
      let copy_item: any = {},
        copy_item2: any = {},
        copy_item2_li: any = {}
      state.complex_list.map((item) => {
        if (item.indexType1 && item.indexType1.id) {
          if (rowSpan1[item.indexType1.id]) {
            copy_item.rowSpan1 += 1
            rowSpan1[item.indexType1.id] += 1
          } else {
            item.rowSpan1 = 1
            copy_item = item
            rowSpan1[item.indexType1.id] = 1
          }
        }
        if (item.indexType2 && item.indexType2.id) {
          if (rowSpan2[item.indexType2.id]) {
            copy_item2.rowSpan2 += 1
            rowSpan2[item.indexType2.id] += 1
          } else {
            item.rowSpan2 = 1
            copy_item2 = item
            rowSpan2[item.indexType2.id] = 1
          }
        }
        if (item.indexType2_li && item.indexType2_li.id) {
          if (rowSpan2_li[item.indexType2_li.id]) {
            copy_item2_li.rowSpan2_li += 1
            rowSpan2_li[item.indexType2_li.id] += 1
          } else {
            item.rowSpan2_li = 1
            copy_item2_li = item
            rowSpan2_li[item.indexType2_li.id] = 1
          }
        }
      })
      // console.log('state.complex_list', state.complex_list)
    }
    const dealDataBefore = (arr) => {
      let obj: any = {}
      for (let i = 0, it; (it = arr[i]); i++) {
        obj.indexType1 = { name: it.name, id: it.id, indexType: 1 }
        if (it.children) {
          for (let i2 = 0, it2; (it2 = it.children[i2]); i2++) {
            obj.indexType2 = { name: it2.name, id: it2.id, indexType: 2, children: [] }
            obj.indexType2_li = null
            state.company_list.map((cp) => {
              obj[`cs${cp.id}`] = {
                score: '',
                indexId: '',
                companyId: cp.id,
              }
            })
            if (it2.children) {
              for (let i3 = 0, it3; (it3 = it2.children[i3]); i3++) {
                if (it3.indexType == '2') {
                  // obj.indexType2.children.push({name:it3.name,indexType:2})
                  obj.indexType2_li = { name: it3.name, id: it3.id, indexType: 2 }
                  if (it3.children) {
                    for (let i4 = 0, it4; (it4 = it3.children[i4]); i4++) {
                      obj.indexType3 = { name: it4.name, id: it4.id, indexType: 3 }
                      obj.annualScore = it4.score
                      obj.annualSumScore = it.score
                      obj.companyScoreSmallSum = it4.companyScoreSmallSum
                      obj.finalScore = it4.finalScore
                      if (it4.companyScoreList) {
                        it4.companyScoreList.map((cs) => {
                          obj[`cs${cs.companyId}`] = {
                            score: cs.score,
                            indexId: it4.id,
                            companyId: cs.companyId,
                          }
                        })
                      }
                      state.complex_list.push(JSON.parse(JSON.stringify(obj)))
                    }
                  } else {
                    obj.indexType3 = null
                    obj.annualScore = null
                    obj.annualSumScore = it.score
                    state.company_list.map((cp) => {
                      obj[`cs${cp.id}`] = {
                        score: '',
                        indexId: '',
                        companyId: cp.id,
                      }
                    })
                    state.complex_list.push(JSON.parse(JSON.stringify(obj)))
                  }
                } else {
                  obj.indexType3 = { name: it3.name, indexType: 3, id: it3.id }
                  obj.companyScoreSmallSum = it3.companyScoreSmallSum
                  obj.finalScore = it3.finalScore
                  obj.annualScore = it3.score
                  obj.annualSumScore = it.score
                  if (it3.companyScoreList) {
                    it3.companyScoreList.map((cs) => {
                      obj[`cs${cs.companyId}`] = {
                        score: cs.score,
                        indexId: it3.id,
                        companyId: cs.companyId,
                      }
                    })
                  }
                  state.complex_list.push(JSON.parse(JSON.stringify(obj)))
                }
              }
            } else {
              obj.indexType3 = null
              obj.annualScore = null
              obj.finalScore = ''
              obj.annualSumScore = 0
              state.company_list.map((cp) => {
                obj[`cs${cp.id}`] = {
                  score: '',
                  indexId: '',
                  companyId: cp.id,
                }
              })
              state.complex_list.push(JSON.parse(JSON.stringify(obj)))
            }
          }
        } else {
          obj.indexType2 = null
          obj.indexType3 = null
          obj.annualScore = null
          state.complex_list.push(JSON.parse(JSON.stringify(obj)))
        }
      }
    }
    const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (row._rowType == 'sumRow') {
        //合计行
        if (columnIndex === 0) {
          return {
            rowspan: 1,
            colspan: 4,
          }
        } else if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3) {
          return {
            rowspan: 0,
            colspan: 0,
          }
        } else if (columnIndex === 4) {
          return {
            rowspan: 1,
            colspan: 2,
          }
        } else if (columnIndex === 5) {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      } else {
        //正常行也不正常
        if (columnIndex === 0) {
          //类指标
          return {
            rowspan: row.rowSpan1 || 0,
            colspan: 1,
          }
        } else if (columnIndex === 1) {
          //模块指标
          return {
            rowspan: row.rowSpan2 || 0,
            colspan: row.indexType2_li ? 1 : 2,
          }
        } else if (columnIndex === 2) {
          if (row.indexType2_li) {
            return {
              rowspan: row.rowSpan2_li || 0,
              colspan: 1,
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        } else if (columnIndex === 5) {
          //年度标准分值

          return {
            rowspan: row.rowSpan1 || 0,
            colspan: 1,
          }
        }
      }
    }
    const headerCellStyle = ({ row, column, rowIndex, columnIndex }) => {
      if (rowIndex == 1) {
        return { display: 'none' }
      }
    }
    const rowStyle = ({ row, rowIndex }) => {
      if (rowIndex % 2 === 0) {
        return { backgroundColor: 'transparent' }
      } else {
        return { backgroundColor: 'rgb(34,58,110)' }
      }
    }
    const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
      if (column.property === 'totalScore') {
        return { color: 'green' }
      }
    }
    return {
      data,
      state,
      zjeharts,
      searchFrom,
      NumberCheck,
      changeHandler,
      updateDataBtn,
      editOrSaveBtn,
      exportExcel,
      ageChange,
      arraySpanMethod,
      headerCellStyle,
      rowStyle,
      cellStyle,
    }
  },
}
</script>
<style lang="scss" scoped>
@import '../boardCss.scss';
:deep(.el-tabs__item) {
  padding: 0;
  color: white;
}
:deep(.el-tabs__item.is-active) {
  color: #409eff;
}
:deep(.el-tabs__nav-wrap::after) {
  background-color: transparent;
}
.table-box {
  :deep(.el-table__fixed-right tbody tr:hover > td) {
    background-color: transparent;
  }
  :deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
    background-color: transparent;
  }
  :deep(.el-table::before) {
    height: 0;
  }
  :deep(.el-table) {
    background-color: transparent;
    color: white;
    .el-table__header thead tr th {
      background-color: rgb(8, 27, 86);
      color: rgba(255, 255, 255, 0.8);
      font-size: 16px;
      font-weight: 650;
    }
    td,
    th.is-leaf {
      border: none;
      font-size: 16px;
      font-weight: 400;
    }
    .tbody tr:hover > td {
      background-color: transparent;
    }
    .el-table__body tr.hover-row > td {
      background-color: transparent;
    }
  }
}

.qwl-table {
  .table-header {
    background: #ccc;
  }
  .table-list {
  }
}

.table-bg {
  .el-table {
    background-color: #0b1545;
  }
  :deep(.el-table tr) {
    color: #fff;
    background-color: #0b1545 !important;
  }
  :deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
    background-color: #0b1545 !important;
  }
  .el-table thead.is-group th {
    color: #fff;
    background-color: #0b1545 !important;
  }
}
.chart-container {
  // background-color: #0b1545;
  background-image: url(../images/container-bg.png);
  background-size: 100% 100%;
}
.table-box {
  background-image: url(../images/table-bg.png);
  background-size: 100% 100%;
}
.table-input {
  outline: none;
}
</style>
